import React from 'react'
import './App.css'
import {Router} from './router'
import {Navigate, Route, HashRouter, Routes} from 'react-router-dom'

const App = () => {

    const generateRoutes = () => {
        let routes: Array<React.ReactElement> = []
        // 遍历Router列表
        Router.forEach((first_route, first_index) => {
            if (first_route.children) { // 第一层路由对象判断是否下面挂有子组件
                let second_routes: Array<React.ReactElement> = [] // 第二层子路由的容器
                first_route.children.forEach((second_route, second_index) => { // 遍历第二层子路由列表
                    if (second_route.component) {  // 第二层是真实路由的情况
                        const SecondComponent = second_route.component // 根据路径懒加载组件
                        second_routes.push(
                            <Route
                                key={second_index}
                                path={second_route.path}
                                element={<SecondComponent/>}
                            />
                        )
                    }
                    if (second_route.children) {  // 第二层是菜单组（非真实路由）的情况
                        second_route.children.forEach((third_route, third_index) => {  // 遍历第三层子路由
                            const ThirdComponent = third_route.component // 根据路径懒加载组件
                            second_routes.push(
                                <Route
                                    key={second_index + third_index}
                                    path={second_route.path + '/' + third_route.path}
                                    element={<ThirdComponent/>}
                                />
                            )
                        })
                    }
                })
                const FirstComponent = first_route.component // 根据路径懒加载组件
                // 子路由列表嵌套进layout组件中
                routes.push(<Route key={first_index} path={first_route.path} element={<FirstComponent/>}>
                    {second_routes}
                </Route>)
            } else {
                // 无 children 单条路由的情况
                const SomeComponent = first_route.component
                routes.push(<Route key={first_index} path={first_route.path} element={<SomeComponent/>}/>)
            }
        })
        return routes
    }


    return (
        <div className="App">
            <HashRouter>
                <Routes>
                    {generateRoutes()}
                    <Route path="/" element={<Navigate replace to="/main/welcome"/>}/>
                    <Route path="*" element={<Navigate replace to="/main/404"/>}/>
                </Routes>
            </HashRouter>
            {/*hello world*/}
        </div>
    )
}

export default App
